package cn.gok.springsecuritydemo4.filter;

import cn.gok.springsecuritydemo4.entity.Permission;
import cn.gok.springsecuritydemo4.entity.Role;
import cn.gok.springsecuritydemo4.service.PermissionService;
import cn.gok.springsecuritydemo4.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;

/**
    自定义权限验证的规则
 */
@Component
public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    PermissionService permissionService;

    @Autowired
    RoleService roleService;

    public final static String ROLE_PREFIX = "ROLE_";

    AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {

        HttpServletRequest request = ((FilterInvocation)object).getRequest();

        //1、获取用户的请求，比如：/user/addUser
        String requestURI = request.getRequestURI();


        //2、获取权限表中所有permission_url
        List<Permission> allPermissions = permissionService.getAllPermissions();

        //3、遍历Permission权限集合，寻找到 用户提交的requestURI 与之对应  permission_url
        for (Permission permission : allPermissions) {

            /*
                AntPathMatcher 对请求地址进行验证
                        match(String pattern, String path)  pattern： 路径规则
                                                            path：   提交的具体路径
                              注意两个顺序一定不能错：
                                    比如 match(/user/{id},/user/1) 返回结果是true
                                    但如果写反了  match(/user/1, /user/{id}) 结果为false
             */
            if (antPathMatcher.match(permission.getPermissionUrl(),requestURI) ){
                //4、如果匹配，则依据Permission表，找到能执行该请求地址的  角色集合
                List<Role> roles = roleService.findRolesByPermissionId(permission.getId());

                String[] roleNames = new String[roles.size()];

                for (int i = 0; i < roleNames.length; i++) {
                    roleNames[i] = ROLE_PREFIX + roles.get(i).getRoleName();
                }
                return SecurityConfig.createList(roleNames);
            }
        }
        return null;
    }


    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
